import 'package:carousel_slider_plus/carousel_slider_plus.dart';
import 'package:expandable_text/expandable_text.dart';
import 'package:flutter/material.dart';
import 'package:hippo_app/models/plant.dart';
import 'package:hippo_app/utils/common_util.dart';
import 'package:hippo_app/values/color_value.dart';
import 'package:hippo_app/values/size_value.dart';
import 'package:hippo_app/values/style_value.dart';
import 'package:hippo_app/widgets/app_header/app_header.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:hippo_app/widgets/app_header/app_transparent_header.dart';
import 'package:hippo_app/widgets/app_scaffold/app_scaffold.dart';
import 'package:hippo_app/widgets/empty/empty.dart';
import 'package:hippo_app/widgets/tag/tag.dart';
import 'package:hippo_app/widgets/title/line_title.dart';
import 'package:timeline_tile/timeline_tile.dart';

class PlantViewPage extends StatefulWidget {
  final Plant arguments;

  const PlantViewPage({super.key, required this.arguments});

  @override
  State<PlantViewPage> createState() => _PlantViewPageState();
}

class _PlantViewPageState extends State<PlantViewPage> {
  @override
  void initState() {
    super.initState();
  }

  Plant plant = Plant(
    id: '001',
    img: 'assets/images/demo.jpg',
    imgList: [
      'assets/images/demo.jpg',
      'assets/images/demo2.jpg',
      'assets/images/demo3.jpg',
    ],
    fertilizerTotal: 9,
    waterTotal: 999,
    aliasName: '香石竹、荷兰石竹、狮头石竹、大花石竹',
    category: '百合科',
    plantingTime: '2025-12-02 20:18:04',
    desc:
        '康乃馨（学名：Dianthus Carnation）：是石竹科、石竹属多年生草本植物，是多种石竹属园艺品种的通称。为多年生草本植物，株高70-100厘米，基部半木质化。整个植株被有白粉，呈灰绿色。茎干硬而脆，节膨大。叶线状披针形，全缘，叶质较厚，上半部向外弯曲，对生，基部抱茎。花通常单生，聚伞状排列。花冠半球形，花萼长筒状，花蕾橡子状，花瓣扇形，花朵内瓣多呈皱缩状，花色有大红、粉红、鹅黄、白、深红等，还有玛瑙等复色及镶边等，有香气。',
  );

  Widget buildHeaderCard() {
    return AppHeader(
      appBar: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            widget.arguments.name ??
                AppLocalizations.of(context)!.plantViewPageTitle,
            style: StyleValue.appBarTitleStyle,
          ),
        ],
      ),
    );
  }

  Widget buildPlantCard() {
    if (plant.imgList != null && plant.imgList!.isNotEmpty) {
      return CarouselSlider(
        options: CarouselOptions(
          height: 350.0,
          viewportFraction: 1.0,
          enlargeCenterPage: true,
          autoPlay: true,
        ),
        items:
            plant.imgList?.map((item) {
              return Builder(
                builder: (BuildContext context) {
                  return Image.asset(
                    width: MediaQuery.of(context).size.width,
                    height: 350,
                    item,
                    fit: BoxFit.cover,
                    //fit: BoxFit.fill,
                  );
                },
              );
            }).toList(),
      );
    } else {
      return Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Image.asset(
          width: MediaQuery.of(context).size.width,
          height: 350,
          'assets/images/logo.png',
          fit: BoxFit.cover,
          //fit: BoxFit.fill,
        ),
      );
    }
  }

  Widget buildLabelCard(Widget child) {
    return Container(
      margin: EdgeInsets.only(top: SizeValue.appContentPadding),
      padding: EdgeInsets.only(
        top: SizeValue.appContentPadding,
        left: SizeValue.appContentPadding,
        right: SizeValue.appContentPadding,
        bottom: SizeValue.appContentPadding,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [StyleValue.defaultCardBoxShadow],
        borderRadius: BorderRadius.all(
          Radius.circular(SizeValue.appBorderRadius),
        ),
      ),
      child: child,
    );
  }

  Widget buildLabelColumn(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(width: 70, child: Text(label, style: StyleValue.defaultStyle)),
        SizedBox(
          width:
              MediaQuery.of(context).size.width -
              SizeValue.appContentPadding * 4 -
              70,
          child: ExpandableText(
            value,
            style: StyleValue.defaultContentStyle,
            expandText: AppLocalizations.of(context)!.expandLabel,
            collapseText: AppLocalizations.of(context)!.collapseLabel,
            maxLines: 4,
            animation: true,
            linkEllipsis: false,
            linkStyle: StyleValue.defaultLinkStyle,
          ),
        ),
      ],
    );
  }

  Widget buildTimeline(String title, List<String> dataList, Widget action) {
    List<Widget> widgets = [LineTitle(title: title, rightWidget: action)];
    if (dataList.isEmpty) {
      widgets.add(Empty());
    } else {
      for (int i = 0; i < dataList.length; i++) {
        widgets.add(
          TimelineTile(
            beforeLineStyle: LineStyle(
              thickness: 2,
              color: ColorValue.appPrimaryShallowColor,
            ),
            indicatorStyle: IndicatorStyle(
              width: 10,
              color: ColorValue.appPrimaryShallowColor,
              indicatorXY: 0.28,
            ),
            alignment: TimelineAlign.start,

            endChild: Container(
              padding: EdgeInsets.only(
                left: SizeValue.appContentPadding,
                right: SizeValue.appContentPadding,
              ),
              constraints: const BoxConstraints(minHeight: 30),
              child: Text(dataList[i], style: StyleValue.defaultContentStyle),
            ),
          ),
        );
      }
    }

    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: widgets,
    );
  }

  Widget buildPlantBaseCard() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        buildLabelCard(
          Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,

                children: [
                  Tag(label: plant.category ?? '-'),
                  Expanded(
                    child: Text(
                      widget.arguments.name ?? '-',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: StyleValue.titleStyle,
                    ),
                  ),
                ],
              ),
              Container(
                padding: EdgeInsets.only(top: SizeValue.appContentPadding),
                child: buildLabelColumn(
                  "${AppLocalizations.of(context)!.plantAliasNameLabel}：",
                  plant.aliasName ?? '-',
                ),
              ),

              Container(
                padding: EdgeInsets.only(top: SizeValue.appContentPadding),
                child: buildLabelColumn(
                  "${AppLocalizations.of(context)!.plantWaterTotalLabel}：",
                  '${plant.waterTotal}次',
                ),
              ),
              Container(
                padding: EdgeInsets.only(top: SizeValue.appContentPadding),
                child: buildLabelColumn(
                  "${AppLocalizations.of(context)!.plantFertilizerTotalLabel}：",
                  '${plant.fertilizerTotal}次',
                ),
              ),
              Container(
                padding: EdgeInsets.only(top: SizeValue.appContentPadding),
                child: buildLabelColumn(
                  "${AppLocalizations.of(context)!.plantPlantingTimeLabel}：",
                  plant.plantingTime ?? '-',
                ),
              ),
              Container(
                padding: EdgeInsets.only(top: SizeValue.appContentPadding),
                child: buildLabelColumn(
                  "${AppLocalizations.of(context)!.plantDescLabel}：",
                  plant.desc ?? '-',
                ),
              ),
            ],
          ),
        ),
        buildLabelCard(
          buildTimeline(
            AppLocalizations.of(context)!.monthWaterRecords,
            [
              '2025-12-11 08:25:26 浇水1次',
              '2025-12-12 08:25:26 浇水1次',
              '2025-12-13 08:25:26 浇水1次',
              '2025-12-14 08:25:26 浇水1次',
              '2025-12-15 08:25:26 浇水1次',
              '2025-12-16 08:25:26 浇水1次',
            ],
            InkWell(child: Text('更多', style: StyleValue.txtActionStyle)),
          ),
        ),
        buildLabelCard(
          buildTimeline(
            AppLocalizations.of(context)!.monthFertilizerRecords,
            [],
            InkWell(
              child: Text(
                AppLocalizations.of(context)!.moreLabel,
                style: StyleValue.txtActionStyle,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildPlantInfo() {
    return Container(
      margin: EdgeInsets.only(
        left: SizeValue.appContentPadding,
        right: SizeValue.appContentPadding,
        bottom: SizeValue.appContentPadding,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [buildPlantBaseCard()],
      ),
    );
  }

  Widget buildMain(BuildContext context) {
    return Expanded(
      child: MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: ListView(
          shrinkWrap: true,
          children: [buildPlantCard(), buildPlantInfo()],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      body: AppTransparentHeader(
        backVisible: true,
        child: Column(children: [buildMain(context)]),
      ),
    );
  }
}
